package nl.saxion.security.transfer;

import java.io.File;
import java.io.IOException;
import nl.saxion.security.connection.Connection;

/**
 * Class for setting up connection
 *
 * @author EII7SCb
 *
 */
public class Transfer {

	protected int comPort;
	protected int dataPort;
	public Connection dataCon;
	public Connection comCon;

	/**
	 * Set up connection
	 * @param comPort
	 * @param dataPort
	 */
	public Transfer(int comPort, int dataPort)
	{
		this.comPort = comPort;
		this.dataPort = dataPort;
	}

	/**
	 * Get object from data stream. Stream will be closed.
	 * @return Object from stream
	 * @throws Exception 
	 */
	public Object getObject() throws Exception
	{
		Object object = null;

		createDataConnection();
		
		object = dataCon.getObject();
		dataCon.close();
		return object;
	}
	
	/**
	 * Receive file from data stream and write to file location.
	 * @param fileName filename and dir (/dir1/dir2/test.txt)
	 */		
	public void getFile(String fileName) throws Exception
	{
			createDataConnection();
			dataCon.getFile(fileName);
	}
	
	/**
	 * Send object file to data stream. Stream will be closed.
	 * @throws IOException 
	 */
	public void sendFile(File file) throws Exception
	{
		createDataConnection();		
		dataCon.sendFile(file);			
	}
	
	/**
	 * Send Object to data stream, Stream will be closed.
	 * @param object
	 * @throws IOException
	 */
	public void sendObject(Object object) throws Exception
	{
		createDataConnection();
		dataCon.sendObject(object);	
	}
	
	
	/**
	 * Create Communication connection
	 * @return Com connection
	 * @throws IOException 
	 */
	public void createComConnection() throws Exception
	{
		 if(!comCon.makeConnection())
			 throw new IOException("Unable start comConnection");
	}
	
	/**
	 * Create Data connection
	 * @return Data connection 
	 * @throws IOException 
	 */
	public void createDataConnection() throws Exception
	{		
		 if(!dataCon.makeConnection())
			 throw new IOException("Unable start comConnection");
	}

}
